﻿using System;
using System.Threading.Tasks;
using App.Core.Domain.BaseObject;
using App.Core.Dtos;
using App.Core;
using App.Core.DataAccess;
using System.Data.Entity;
using App.Core.Domain;
using Omu.ValueInjecter;
using App.Core.Common;
using System.Linq;
using EntityFramework.Extensions;
using System.Linq.Expressions;

namespace App.Services.Impls
{
    public partial class OrderServiceImpl : AppServiceBase,IOrderService
    {
        public async Task<OperationResult> CreateOrder(OrderDto dto, Guid? userId = null)
        {
            using (var db = new Db())
            {
                var redeemCode = await db.RedeemCode.Include("Package").SingleOrDefaultAsync(s => s.CodeNumber == dto.RedeemCode);

                var entity = new Order();
                entity.InjectFrom(dto);
                entity.OrderSN = BillNumberBuilder.NextBillNumber();
                entity.Amount = redeemCode.Package.Price;
                entity.RedeemCodes = dto.RedeemCode;
                if (userId.HasValue) entity.CreatorUserId = userId;
                db.Order.Add(entity);

                await db.SaveChangesAsync();

                //更新兑换码使用状态
                if (redeemCode != null) {
                    redeemCode.IsExchange = true;
                    redeemCode.ExchangeUserId = userId.HasValue ? userId : AppSession.UserId;
                    redeemCode.ExchangeTime = DateTime.Now;
                    redeemCode.ExchangeOrderId = entity.Id;
                    redeemCode.LastModifierUserId = userId.HasValue ? userId : AppSession.UserId;
                }

                var result = await db.SaveChangesAsync();

                //插入常用地址
                if (await db.Address.CountAsync(s => s.CreatorUserId == userId && s.ConsigneePhone == dto.ConsigneePhone && s.Consignee == dto.Consignee) == 0)
                {
                    var addressDto = new AddressDto();
                    addressDto.InjectFrom(dto);
                    var address = new Address();
                    address.InjectFrom(addressDto);
                    address.CreatorUserId = userId.HasValue ? userId : AppSession.UserId;

                    db.Address.Add(address);

                    await db.SaveChangesAsync();
                }

                return new OperationResult() { success = result > 0 };
            }
        }

        public async Task DeleteAsync(Guid[] idList)
        {
            using (var db = new Db())
            {
                var orders = db.Order.Where(s => idList.Contains(s.Id)).ToList();
                db.Order.RemoveRange(orders);
                await db.SaveChangesAsync();
            }
        }

        public async Task<AddressDto> GetLastAddressAsync(Guid? userId)
        {
            using (var db = new Db())
            {
                if (!userId.HasValue) return new AddressDto();

                var lastOrder = await db.Order.Where(s=>s.CreatorUserId == userId).OrderByDescending(s => s.CreationTime).FirstOrDefaultAsync();
                var address = new AddressDto { };
                if(lastOrder != null) address.InjectFrom(lastOrder);

                return address;
            }
        }

        public async Task<Order> GetOrderAsync(string orderSN)
        {
            using (var db = new Db())
            {
                return await db.Order.FirstOrDefaultAsync(s=>s.OrderSN == orderSN);
            }
        }

        public async Task<Order> GetOrderAsync(Guid id)
        {
            using (var db = new Db())
            {
                return await db.Order.FindAsync(id);
            }
        }

        public async Task<OperationResult> SetOrderStatus(Guid id, OrderStatusDto dto)
        {
            using (var db = new Db())
            {
                var entity = await db.Order.FindAsync(id);
                if (entity == null)
                {
                    return new OperationResult() { success = false, message = string.Format("找不到该记录Id为{0}的记录", id) };
                }

                entity.OrderStatus = dto.OrderStatus;
                if (!string.IsNullOrEmpty(dto.TrackingNumber))
                    entity.TrackingNumber = dto.TrackingNumber;

                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }

        public async Task<OperationResult> UpdateOrder(Guid id, OrderDto dto)
        {
            using (var db = new Db())
            {
                var entity = await db.Order.FindAsync(id);
                if (entity == null)
                {
                    return new OperationResult() { success = false, message = string.Format("找不到该记录Id为{0}的记录", id) };
                }

                entity.InjectFrom(dto);

                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }
    }
}
